package workforce.limousine.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import java.util.ArrayList;
import java.util.List;
import limousine.vo.Users;
import limousine.util.Service;
import limousine.util.Token;
import limousine.vo.UserContext;

public class Signoff extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        System.out.println("***Signoff");
        HttpSession session = request.getSession();

        Service service = new Service();
        service.setServletContext(this.getServlet().getServletContext());
        DataSource ds = service.getDataSource();
        service.removeMsgAttribute(request, session, "");

        Users user = (Users) session.getAttribute(Token.USER_SESSION);
        if (user != null) {
            service.updateOfflineStatus(ds, user.getId());//update last login

            //remove from user context list            
            List<UserContext> userContextList = (ArrayList<UserContext>) this.getServlet().getServletContext().getAttribute(
                    Token.USER_CONTEXT_LIST);
            //System.out.println("----userContextList " + userContextList);
            if (userContextList != null) {
                if (userContextList.size() > 0) {
                    for (int i = 0; i < userContextList.size(); i++) {
                        if (userContextList.get(i).getUserID().equals(user.getId())) {
                            userContextList.remove(i);
                        }
                    }
                    this.getServlet().getServletContext().setAttribute(Token.USER_CONTEXT_LIST, userContextList);
                }
            }
            //remove from user context list



            //System.out.println("--SESSION EXPIRE--");
            //return mapping.findForward(Token.SESSION_EXPIRE);
        }
        /*if(!user.getUser_name().equals("admin")){
        System.out.println("--Not admin Hack--");
        return mapping.findForward(Token.SESSION_EXPIRE);
        }*/

        session.removeAttribute(Token.USER_SESSION);
        session.removeAttribute(Token.USER_CONTROL);

        //        DataSource ds = this.getDataSource(request, Token.DATASOURCE_NAME);


        String callbackUrl = request.getParameter("callbackUrl");
        if (callbackUrl != null && callbackUrl.length() > 0) {
            ActionForward af = new ActionForward(callbackUrl, true);
            return af;
        } else {

            return mapping.findForward(Token.SUCCESS);
        }
    }
}
